package com.itshen.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo {

    public static void main(String[] args) {
        Factory2 factory = new Factory2();
        // A和B消费
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    factory.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    factory.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();

        // C和D生产
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    factory.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    factory.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}

class Factory2 {

    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition c = lock.newCondition();

    public void increment() throws Exception {
        lock.lock();
        try {
            //1 判断，用while防止虚假唤醒
            while (number != 0) {
                // 等待
                c.await();
            }
            //2 干活
            number++;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            //3 通知
            c.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() throws Exception {
        lock.lock();
        try {
            //1 判断，用while防止虚假唤醒
            while (number == 0) {
                // 等待
                c.await();
            }
            //2 干活
            number--;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            //3 通知
            c.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
